package com.Pan.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RunRepeatService
 *
 * @Description: 重跑服务类
 *
 * @Author yangtao
 *
 * @Date 2021/8/20
 **/

@Slf4j
public class BusinessThreadPool implements Executor {

    /**
     * 执行器实例
     */
    private static volatile Executor mExecutor;

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));;
    private static final int MAX_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_TIME = 120;
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
    private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<Runnable>();

    private static ThreadPoolExecutor mThreadPoolExecutor;

    private BusinessThreadPool() {
        long keepAlive = KEEP_ALIVE_TIME;
        mThreadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, keepAlive, TIME_UNIT, WORK_QUEUE);
    }

    @Override
    public void execute(final Runnable runnable) {
        mThreadPoolExecutor.submit(runnable);
    }

    @Override
    public Future execute(Callable callable) {
        return mThreadPoolExecutor.submit(callable);
    }

    public static Executor getInstance() {
        if (mExecutor == null) {
            mExecutor = new BusinessThreadPool();
        }
        return mExecutor;
    }
}
